<?php

namespace app\Admin\controller;

use app\Admin\model\Images;
use think\Controller;
use think\Exception;
use think\Request;
use yii\debug\models\search\Db;

class Good extends Controller
{
    /**
     * 显示资源列表
     *
     * @return \think\Response
     */
    public function index()
    {
        $key = input('goods_name');
        $where = [];
        if (!empty($key)){
            $where['goods_name'] = ['like',"%$key%"];
        }
        $data = \app\Admin\model\Good::with('brand,type,images')->where($where)->paginate(2,false,[
            'query'=>['goods_name'=>$key]
        ]);
        return  view('show',['data'=>$data]);
    }

    /**
     * 显示创建资源表单页.
     *
     * @return \think\Response
     */
    public function create()
    {
        //
    }

    /**
     * 保存新建的资源
     *
     * @param  \think\Request  $request
     * @return \think\Response
     */
    public function save(Request $request)
    {
        //
    }

    /**
     * 显示指定的资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function read($id)
    {
        //
    }

    /**
     * 显示编辑资源表单页.
     *
     * @param  int  $id
     * @return \think\Response
     */

    public function detail()
    {
      $id = input('id');
      $this->success('正在跳转请稍后',"/admin/good/edit/id/$id",[],3);
    }



    public function edit($id)
    {
        $data = \app\Admin\model\Good::with('brand,type,images')->find($id);
        return view('detail',['data'=>$data]);
    }

    /**
     * 保存更新的资源
     *
     * @param  \think\Request  $request
     * @param  int  $id
     * @return \think\Response
     */
    public function update(Request $request, $id)
    {
        //
    }

    /**
     * 删除指定资源
     *
     * @param  int  $id
     * @return \think\Response
     */
    public function delete($id)
    {
        $data = \app\Admin\model\Good::find($id);
        \think\Db::startTrans();
        try {
            if ($data['is_hot'] == 1){
                $this->error('推荐状态不能删除','/admin/good/index');
            }else{
                \app\Admin\model\Good::destroy($id);
                Images::where('good_id',$id)->delete();
            }
            \think\Db::commit();
            $this->success('操作成功',"/admin/good/index");
        }catch (Exception $e){
            \think\Db::rollback();
            $this->success('操作失败',"/admin/good/edit/id/$id");
        }
    }
}
